﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Hammock.Authentication.OAuth;
using Hammock;
using Hammock.Web;
using System.Collections.Generic;

namespace Tsina
{
    public class OAuthHelper
    {
        public static void AccessProtectedResource(string url, WebMethod method, List<KeyValuePair<string, string>> postData, RestCallback callback, object userState)
        {
            if (string.IsNullOrEmpty(ConfigHelper.AccessToken) == true)
            {
                throw new Exception("No Access Token!");
            }

            var credentials = new OAuthCredentials()
            {
                Type = OAuthType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = ConfigHelper.AppKey,
                ConsumerSecret = ConfigHelper.AppSecret,
                Token = ConfigHelper.AccessToken,
                TokenSecret = ConfigHelper.AccessTokenSecret
            };

            var client = new RestClient();

            var request = new RestRequest()
            {
                Path = url,
                Credentials = credentials,
                Method = method,
            };

            if (method == WebMethod.Post && postData != null && postData.Count > 0)
            {
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

                foreach (KeyValuePair<string, string> item in postData)
                {
                    request.AddParameter(item.Key, item.Value);
                }
            }

            client.BeginRequest(request, callback, userState);
        }
    }
}
